import {
  ds
} from "~/tools/data"
import {
  users
} from "~/tools/users"
import {
  pages
} from '~/tools/pages'
import {
  nav2
} from "~/tools/nav2"
import {
  ui
} from "~/tools/ui"

Page({
  data: {
    item: {},
    mod: {},
    errMsg: "",
    group: ['showPromotion', 'linkSel', 'buyTicket', 'goodsGroup']
  },
  async init() {
    const {
      id,
      index
    } = this.data
    const that = this
    ds.coll('module').where({
      _id: ds.cmd.eq(id)
    }).get({
      success: function (res) {
        if (res.data && res.data.length > 0) {
          that.setData({
            mod: res.data[0],
            item: res.data[0].slides[index]
          })
        }
      }
    });

  },
  backClick() {
    pages.back()
  },
  saveClick() {
    const {
      item
    } = this.data
    pages.back(prePage => {
      prePage.setAction(item)
    })
  },
  delClick() {
    const {
      id,
      mod,
      index
    } = this.data
    mod.slides.splice(index)
    ds.cloudUpdate('module', id, mod, res =>
      pages.back(prePage => {
        prePage.init()
      }))
  },
  onChooseLink() {
    wx.navigateTo({
      url: '/pages/common/goodsManage/index',
    })
  },
  onLinkTap(e) {
    const link = e.target.dataset.link
    if (!link) return
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${link}`,
    })
  },
  showTicketTap() {
    const item = this.data.item
    item.showTicket = !item.showTicket
    this.setData({
      item
    })
  },
  chooseGroup(name) {
    const {
      item,
      group
    } = this.data
    if (!group[name]) group.push(name)

    item[name] = !item[name]
    if (item[name]) {
      group.forEach(element => {
        if (element == name) return
        item[element] = false
      });
    }
    this.setData({
      item
    })
  },
  selTap(e) {
    const name = ui.eventData(e, 'name')
    this.chooseGroup(name)
  },
  goodsGroupInput(e) {
    const {
      item
    } = this.data
    item.goodsGroup = e.detail.value
    this.setData({
      item
    })
    if (!item.goodsGroupSel) this.chooseGroup('goodsGroupSel')
  },
  nav2PromotionTap() {
    const item = this.data.item
    item.showPromotion = !item.showPromotion
    if (item.showPromotion) item.linkSel = false
    this.setData({
      item
    })
  },
  onTextChange(e) {
    const text = e.detail.value
    const {
      item
    } = this.data
    item.text = text
    this.setData({
      item
    })
  },
  goodsSelected(data) {
    const {
      item
    } = this.data
    if (data) {
      item.title = data.title
      item.link = data.id
    }
    this.setData({
      item
    })
    if (!item.linkSel) this.chooseGroup('linkSel')
  },
  onLoad(option) {
    this.setData({
      item: JSON.parse(option.data)
    })

    this.init();
  },
});